package wat.serwerapp.connection;

import java.io.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.AuthenticationException;
import javax.naming.NamingException;
import wat.ziszcommon.transport.Contener;
import wat.ziszcommon.transport.Module;
import wat.serwerapp.main.Parameters;
import wat.serwerapp.usermgmt.UserManager;
import wat.serwerapp.usermgmt.UserManager.User;


/**
 *
 * @author Tarni & P.B. & L.G. & K.K.
 */
public class Receiver {

   public static Object login(/*String sessionID, */String userName, String password) {
      String userNameD = "";
      try {
         User user = UserManager.getUser(userName, password);
         //sesMngr.assignVerifiedUser(sessionID, user);
         Map<String, String> rights = user.getAllRights();
         Set<String> keys = rights.keySet();

         Contener contener = new Contener(user.getFullName());

         for (String name : keys) {
            char oldChar = '.';
            char newChar = '/';

            String path = rights.get(name);
            String repoDir = Parameters.getInstance().getRepositoryDir();
            String fullPath = repoDir + path.replace(oldChar, newChar) + ".class";
            File clazz = new File(fullPath);
            if (clazz.exists()) {
               int lenght = Long.valueOf(clazz.length()).intValue();
               byte[] clazzBytes = new byte[lenght];
               FileInputStream fis = new FileInputStream(clazz);
               int r = fis.read(clazzBytes);
               if (r != lenght) {
                  System.out.println("BLAD PODCZAS LADOWANIA PLIKU");
               }
               Module module = new Module(name, path);
               String filename = clazz.getName();
               filename = filename.substring(0, filename.length() - 6);
               System.out.println("Class name:::" + filename);
               File[] linked = clazz.getParentFile().listFiles(new MyFilenameFilter(filename + "$"));

               module.addClazz(clazz.getName(), clazzBytes);

               for (File file : linked) {
                  System.out.println("Linked class:::" + file.getName());

                  int linkedLenght = Long.valueOf(file.length()).intValue();
                  byte[] linkedClazzBytes = new byte[linkedLenght];
                  FileInputStream linkedfis = new FileInputStream(file);
                  int lr = linkedfis.read(linkedClazzBytes);
                  if (lr != linkedLenght) {
                     System.out.println("BLAD PODCZAS LADOWANIA PLIKU");
                  }
                  module.addClazz(file.getName(), linkedClazzBytes);
               }

               String resPath = clazz.getParentFile().getPath() + "\\resources\\" + filename + ".properties";
               File res = new File(resPath);
               if (res.exists()) {
                  System.out.println("RESOURCE:::" + resPath);
                  int resLenght = Long.valueOf(res.length()).intValue();
                  byte[] resClazzBytes = new byte[resLenght];
                  FileInputStream resfis = new FileInputStream(res);
                  int rr = resfis.read(resClazzBytes);
                  if (rr != resLenght) {
                     System.out.println("BLAD PODCZAS LADOWANIA PLIKU");
                  }
                  module.setResource(resClazzBytes);
               } else {
                  System.out.println("BRAK PLIKU RESOURCE!!!");
               }

               contener.addModule(module);
               System.out.println(path + " (" + name + ") OK.");
            } else {
               System.out.println("Klasa " + path + " nie istnieje! (" + name + ")");
            }
         }

         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         ObjectOutputStream oos = new ObjectOutputStream(baos);

         oos.writeObject(contener);
         byte[] serialized = baos.toByteArray();
         return serialized;
      }  catch (IOException ex) {
         Logger.getLogger(Receiver.class.getName()).log(Level.SEVERE, "Blad podczas serializacji", ex);
         return "Exception";
      }  catch (AuthenticationException ae) {
         Logger.getLogger(Receiver.class.getName()).log(Level.SEVERE, "login err (user="+ userNameD +")", ae);
         //SessionManager pki = SessionManager.getInstance();
         //pki.abandonSession(sessionID);
         return "UnauthorizedAcces";
      }  catch (NamingException ex) {
         Logger.getLogger(Receiver.class.getName()).log(Level.SEVERE, "LDAP unreachable", ex);
         return "MethodException";
      }
   }

   static class MyFilenameFilter implements FilenameFilter {

      private String prefix;

      public MyFilenameFilter(String prefix) {
         this.prefix = prefix;
      }

      public boolean accept(File dir, String name) {
         if (name.startsWith(prefix)) {
            return true;
         } else {
            return false;
         }
      }
   }
}
